package com.edu.admin.service;

import com.edu.admin.entity.SysAdmin;
import com.edu.admin.mapper.AdminMapper;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

/**
 * 身份校验
 * 
 * @author Wangjiong
 * 
 */
@Component(value="AdminDetailsService")
public class AdminDetailsService implements UserDetailsService {
	@Autowired
	AdminMapper adminMapper;
	@Autowired
	RoleMenuService roleMenuService;

    @Override
    public SysAdmin loadUserByUsername(String name) throws UsernameNotFoundException {
    	SysAdmin sysAdmin = adminMapper.findAdminByUsername(name);
        	
        if (sysAdmin == null) {
            throw new UsernameNotFoundException(String.format("No userDetail found with username '%s'.", name));
        }
        
        List<GrantedAuthority> authorities = new ArrayList<>();
        
        String url = roleMenuService.getUrlsByRoleId(sysAdmin.getRoleId());
        String[] urls = url.split(",");
 		for (int i= 0 ; i<urls.length ; i++)
 		{	if (!urls[i].isEmpty())
 			{
 				authorities.add(new SimpleGrantedAuthority(urls[i]));
 			}
 		}
 		sysAdmin.setAuthorities(authorities);
 		sysAdmin.setRoleUrls(url);
 		
        return sysAdmin;
    }
}
